// 导包
const express = require('express')

const knex = require('knex')({
    client: 'mysql',
    connection: {
        host: '127.0.0.1',
        user: 'root',
        password: 'root',
        database: 'gloryhero',
    }
})
const multer = require('multer')
const path = require('path')
const fs = require('fs')

const jwt = require('jsonwebtoken')
const secretKey = 'linliqun'


// 服务器搭建
const server = express()
// 中间件部分
server.use(express.static(path.join(__dirname, 'www')))
server.use(express.urlencoded({
    extended: false
}))
const upload = multer({
    dest: path.join(__dirname, 'www', 'uploads/')
})
// 登陆接口
server.post('/login', (req, res) => {
    let {
        username,
        password
    } = req.body

    if (username && password) {
        knex('userinfo').select('username','password').where({username})
        .then((result)=>{
            if(result.length>0){
                if(password==result[0].password){
                    const token=jwt.sign({
                        appName:'gloryhero',
                        food:'土豆'

                    },secretKey,{
                        expiresIn:'1h'

                    }
                    )
                    res.send({
                        code:200,
                        msg:'登陆成功',
                        
                        token
                    })
                }else{
                    res.send({
                        code:400,
                        msg:'用户名或密码错误'
                    })
                }
            }else{
                res.send({
                    code:400,
                    msg:'宁还没有注册'
                })
            }
        })
        }else{
            res.send({
                code:400,
                msg:'username与password的参数是必须的'
            })
        }
        })
// 注册接口
server.post('/register', (req, res) => {
    let {
        username,
        password
    } = req.body
    knex('userinfo').select().where({username}).then((result) => {
        if (result.length > 0) {
            res.send({
                code: 400,
                msg: '该用户名已存在'
            })
        } else {
            knex('userinfo').insert({
                username,
                password
            }).then(() => {
                res.send({
                    code: 200,
                    msg: '注册成功',
                    username,
                    password
                })
            })
        }


    })
})

// 中间件  中间件之后的接口都需要token token生效会让所有接口都需要token 导致登陆接口不能登陆 所以放在登陆接口之后
server.use((req, res, next) => {
    const token = req.headers.authorization;
    jwt.verify(token, secretKey, (err) => {
        if (!err) {
            next()
        } else {
            res.send({
                code: 403,
                msg: '无效登录'
            })
        }
    })
})

// 获得所有英雄接口
server.get('/getAllHeros', (req, res) => {
    knex('heroinfo').select('id', 'heroname', 'heroskill', 'heroicon')
        .where({
            isDelete: 0
        })
        .then((result) => {
            res.send({
                code: 200,
                data: result
            })
        })
        .catch((err) => {
            res.send({
                code: 201,
                msg: '获取英雄成功'
            })
        })
})
// 模糊查询英雄接口
server.get('/getHeroByName', (req, res) => {
    let {
        keyword
    } = req.query
    knex('heroinfo').select('id', 'heroname', 'heroskill', 'heroicon')
        .where('heroname', 'like', `%${keyword}%`)
        .andWhere({
            isDelete: 0
        })
        .then((result) => {
            if (result.length > 0) {
                res.send({
                    code: 200,
                    msg: '获得英雄成功',
                    data: result
                })
            } else {
                res.send({
                    code: 202,
                    msg: '没有相关英雄信息',

                })
            }
        })
        .catch((err) => {
            res.send({
                code: 400,
                msg: '无法获得英雄信息',

            })
        })
})

// 后端删除英雄接口
server.post('/delHeroById', (req, res) => {
    let {
        id
    } = req.body
    knex('heroinfo').update({
            isDelete: 1
        }).where({
            id
        })
        .then((result) => {
            res.send({
                code: 200,
                msg: '英雄删除成功'
            })
        })
        .catch(() => {
            res.send({
                code: 400,
                msg: '英雄删除失败'
            })
        })
})




// 新增英雄接口post/formData
server.post('/addHero', upload.single('heroicon'), (req, res) => {
    let {
        heroname,
        heroskill
    } = req.body
    let heroicon = 'uploads/' + req.file.filename

    knex('heroinfo').insert({
        heroname,
        heroskill,
        heroicon
    }).then((result) => {
        res.send({
            code: 200,
            msg: '新增英雄成功'
        })
    }).catch((err) => {
        res.send({
            code: 403,
            msg: '新增英雄失败'
        })
    })
})

// 后台获得指定英雄数据
server.get('/getHeroById', (req, res) => {
    let {
        id
    } = req.query
    knex('heroinfo').select('heroicon', 'heroname', 'heroskill')
        .where({
            id
        })
        .then((result) => {
            res.send({
                code: 200,
                msg: '获取英雄成功',
                data: result
            })
        })
        .catch((err) => {
            res.send({
                code: 400,
                msg: '获取英雄失败'
            })
        })



})
// 后台完成指定接口编辑
server.post('/editHero', upload.single('heroicon'), (req, res) => {
    let {
        heroname,
        heroskill,
        id
    } = req.body
    let heroicon = 'uploads/' + req.file.filename
    knex('heroinfo').update({heroname, heroskill, heroicon}).where({
            id
        }).then((result) => {
            res.send({
                code: '200',
                msg: '编辑成功'
            })
        })
        .catch((err) => {
            res.send({
                code: '400',
                msg: '编辑失败'
            })
        })
})


server.listen(4099, () => {
    console.log('服务开启 端口4099');

})